package MyThread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 线程池核心点；复用机制
 * 1.提前创建好固定的线程数量一直在运行状态--------死循环实现
 * 2.提交的线程任务缓存到一个并发队列的集合中，交给我们正在运行的线程执行
 * 3.正在运行的线程就会从队列中获取该任务
 */
public class MyExecutors {
    private List<WorkThread> workThreads;
    private BlockingDeque<Runnable> runnableDeque;

    public MyExecutors(int maxThreadCount, int dequeSize) {
        runnableDeque = new LinkedBlockingDeque<>(dequeSize);
        workThreads = new ArrayList<>(maxThreadCount);
        for (int i = 0; i < maxThreadCount; i++) {
            new WorkThread().start();
        }
    }

    class WorkThread extends Thread {
        @Override
        public void run() {
            while (true) {
                Runnable poll = runnableDeque.poll();
                if (poll != null) {
                    poll.run();
                }
            }
        }
    }

    public boolean execute(Runnable command) {
        return runnableDeque.offer(command);
    }

    public static void main(String[] args) {
        MyExecutors myExecutors = new MyExecutors(2, 20);
        for (int i = 0; i < 10; i++) {
            final int finalI=i;
            myExecutors.execute(() -> System.out.println(Thread.currentThread().getName()+","+finalI));

        }
    }
}
